package com.coocaa.x.service.litepush;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Build;

import com.coocaa.x.framework.app.CoocaaApplication;
import com.coocaa.x.framework.data.JObject;
import com.coocaa.x.framework.utils.Android;
import com.coocaa.x.framework.utils.LogUtils;
import com.skyworth.framework.skysdk.push.SkyPush;

import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * Created by lu on 15-7-27.
 */
public class CoocaaPUSH extends BroadcastReceiver {
    public static interface ICoocaaPUSH {
        void onMSG(String msg);

        void onPushId(String pushId);
    }

    private static CoocaaPUSH instance = null;

    private static final String APPID = "2166620f-8842-4c8f-8d7a-19783f867f1c";
    private static final String TOKENID = "d9276530-815c-466d-bfb9-98ae59aa6f19";

    private int regResult = 0;
    private ICoocaaPUSH listener = null;


    public static synchronized void init(ICoocaaPUSH i) {
        if (instance != null)
            return;
        instance = new CoocaaPUSH(i);
        IntentFilter filter = new IntentFilter();
        filter.addAction("com.coocaa.push.BC.REG");
        filter.addAction("com.coocaa.push.BC.MSG");
        CoocaaApplication.getContext().registerReceiver(instance, filter);
        CoocaaApplication.post(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                SkyPush.registID(CoocaaApplication.getContext(), APPID, TOKENID);
            }
        });
    }

    public synchronized static final void uninit() {
        if (instance != null) {
            try {
                CoocaaApplication.getContext().unregisterReceiver(instance);
            } catch (Exception e) {
                e.printStackTrace();
            }
            instance = null;
        }
    }

    public CoocaaPUSH(ICoocaaPUSH i) {
        super();
        LogUtils.d("CoocaaPUSH", "CoocaaPUSH init listener:" + i + "   pkg:" + CoocaaApplication.getContext().getPackageName());
        listener = i;
        final ScheduledThreadPoolExecutor checker = new ScheduledThreadPoolExecutor(1);
        checker.scheduleAtFixedRate(new Runnable() {
            @Override
            public void run() {
                switch (regResult) {
                    case 1: {
                        LogUtils.d("CoocaaPUSH", "<coocaapush register result>" + regResult + " success!");
                        checker.shutdown();
                        break;
                    }
                    case 0: {
                        LogUtils.d("CoocaaPUSH", "<coocaapush register result>" + regResult + " register has no return! just wait and try again!");
                        break;
                    }
                    case -1: {
                        LogUtils.d("CoocaaPUSH", "<coocaapush register result>" + regResult + " network is not connected! just wait and try again!");
                        SkyPush.registID(CoocaaApplication.getContext(), APPID, TOKENID);
                        break;
                    }
                    case -2: {
                        LogUtils.d("CoocaaPUSH", "<coocaapush register result>" + regResult + " server can not be connected! just wait and try again!");
                        SkyPush.registID(CoocaaApplication.getContext(), APPID, TOKENID);
                        break;
                    }
                    case -3: {
                        LogUtils.d("CoocaaPUSH", "<coocaapush register result>" + regResult + " wrong appid and token! not more try!");
                        checker.shutdown();
                        break;
                    }
                    default: {
                        LogUtils.d("CoocaaPUSH", "<coocaapush register result>" + regResult + " unknow error ! not more try!");
                        checker.shutdown();
                        break;
                    }
                }
            }
        }, 5000, 20000, TimeUnit.MILLISECONDS);
    }

    private static class RegPushExtra extends JObject {
        public String skymid, skymodel, skytype, mac;
        public String versionCode, versionName, channel;
        public int androidVersion;
    }

    private static String getDeviceChannel() {
        Context context = CoocaaApplication.getContext();
        String channel = (String) Android.getMetaData(context, context.getPackageName(),
                "UMENG_CHANNEL");
        if (channel == null || channel.equals("")) {
            LogUtils.e("getDeviceChannel failed,ues Common instead!!");
            channel = "Common";
        }
        return channel;
    }

    @Override
    public void onReceive(Context context, Intent intent) {
        if (intent.getAction().equals(SkyPush.BC_COOCAAPUSH_MSG)) {
            String msg = intent.getStringExtra(SkyPush.MSG_RESULT_KEY);
            LogUtils.i("CoocaaPUSH", "msg======" + msg + "   listener:" + listener);
            if (listener != null)
                listener.onMSG(msg);
        } else if (intent.getAction().equals(SkyPush.BC_COOCAAPUSH_REGISTER)) {
            int result = intent.getIntExtra(SkyPush.REGID_RESULT_KEY, 0);
            regResult = result;
            final String rid = intent.getStringExtra(SkyPush.REGID_RESULT_REGID_KEY);
            LogUtils.i("CoocaaPUSH", "result ===" + regResult + ",rid===" + rid + " " + (listener != null));
            if (listener != null)
                listener.onPushId(rid);
            LogUtils.i("CoocaaPUSH", "result ===" + regResult + ",rid===" + rid);

            CoocaaApplication.post(new Runnable() {
                @Override
                public void run() {
                    RegPushExtra extra = new RegPushExtra();
                    CoocaaApplication.DeviceModeMidType t = CoocaaApplication.getDeviceModeMidType();
                    extra.skymid = t.skymid;
                    extra.skymodel = t.skymodel;
                    extra.skytype = t.skytype;
                    extra.mac = CoocaaApplication.getMAC();
                    extra.channel = getDeviceChannel();
                    extra.versionCode = CoocaaApplication.getAppVersionCode();
                    extra.versionName = CoocaaApplication.getAPPVersion();
                    extra.androidVersion = Build.VERSION.SDK_INT;
                    boolean result = CoocaaApplication.getCoocaaWebService().getGPushWebService().regPushID(rid, extra.toJSONString(), 2);
                    LogUtils.i("CoocaaPUSH", "regPushID result===" + result + " rid===" + rid);
                    //注册rid session到应用圈后台 用以接收push消息
                }
            });
        }
    }
}
